package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {


        CreateOrderContext createOrderContext = ((CreateOrderContext) context);
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        if (CollectionUtils.isEmpty(createOrderContext.getBuyProductIds())) {
            buyProductIds = new LinkedList<>();
            for (CartProductDto cartProductDto : cartProductDtoList) {
                buyProductIds.add(cartProductDto.getProductId());
            }
        }
        buyProductIds.sort(Long::compareTo);
        List<Stock> stocks = stockMapper.findStocksForUpdate(buyProductIds);

        //判断是否超过限购数量
        for (Stock stock : stocks) {
            for (CartProductDto cartProductDto : cartProductDtoList) {
                if (cartProductDto.getProductId().equals(stock.getItemId()) && cartProductDto.getProductNum() > stock.getRestrictCount()) {
                    throw new BizException("超过商品限购数量");
                }
            }
        }

        //判断商品库存是否存在
        if (CollectionUtils.isEmpty(stocks)) throw new BizException(OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode(), "商品库存未初始化");
        if (stocks.size() != buyProductIds.size()) throw new BizException(OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode(),"部分商品库存未初始化");

        //锁库存
        int size = 0;
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Stock stock = new Stock();
            stock.setItemId(cartProductDto.getProductId());
            stock.setLockCount(cartProductDto.getProductNum().intValue());
            stock.setStockCount(-cartProductDto.getProductNum());
            try {
                size = stockMapper.updateStock(stock);
                if (buyProductIds.size() > size) throw new BizException();
                orderItemMapper.updateStockStatus(3, createOrderContext.getOrderId());
            } catch (Exception e) {
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
            }
        }
        return true;
    }
}